<?php
class Checkout extends CS_Controller
{
    public function _init()
    {
        $this->load->helper('validation');
        $this->load->library('stream/scenicstream', null, 'scenicstream');
        $this->load->model('scenery_base_model', 'scenery_base');
        $this->load->model('goods_base_model', 'goods_base');
        $this->load->model('scenic_category_model', 'scenic_category');
        $this->load->model('region_model', 'region');
        $this->load->model('visitor_model', 'visitor');
        $this->load->model('order_base_model', 'order_base');
        $this->load->model('pay_record_model', 'pay_record');
        $this->load->model('order_profit_model', 'order_profit');
        $this->load->model('order_source_model', 'order_source');
        $this->load->model('make_code_model', 'make_code');
        $this->load->model('user_account_model', 'user_account');
    }
    
    /**
     * 下单页面
     */
    public function confirm()
    {
        $data = array();
        $this->load->view('scenic/checkout/confirm', $data);
    }
    
    /**
     * 确认订单门票
     */
    public function orderTicket()
    {
        $scenicId = $this->input->post('scenicId');
        $ticketId = $this->input->post('ticketId');
        $result = $this->scenery_base->findBySid($scenicId);
        if ($result->num_rows() <= 0) {//景区不存在，则跳转到首页
            echo json_encode(array(
                'status' => false,
                'messages' => $this->config->www_base_url
            ));exit;
        }
        $result2 = $this->goods_base->findByGoodsId($ticketId);
        if ($result2->num_rows() <= 0) { //如果为查询到当前门票则弹框选择其它门票
            echo json_encode(array(
                'status' => false,
                'messages' => false
            ));exit;
        }
        $data['tickets'] = $result2->result();
        $data['weekday'] = array('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六');
        echo json_encode(array(
            'status'   => true,
            'messages' => $this->load->view('scenic/checkout/orderTicket', $data, true)
        ));exit;
    }
    
    /**
     * 弹框
     */
    public function ticketPop()
    {
        $scenicId = $this->input->post('scenicId');
        $ticketId = $this->input->post('ticketId');
        $buyticket = $this->input->post('buyticket');
        $result = $this->scenery_base->findBySid($scenicId);
        if ($result->num_rows() > 0) {
            $sceneryBase = $result->row(0);
            $result1 = $this->goods_base->findByUidParams(array('uid'=>$sceneryBase->uid, 'orderby'=>'cat_id ASC, goods_id ASC'));
            $goodsBase = array();
            foreach ($result1->result() as $item) {
                $goodsBase[$item->cat_id][] = $item;
            }
            $data['goodsBase'] = $goodsBase;
        } else {
            $data['goodsBase'] = array();
        }
        $data['goods_id'] = $buyticket ? array_keys($buyticket) : array();
        $data['cat_id'] = array(1=>'普通票', 2=>'联票' ,8=>'年票', 16=>'团队票');
        $data['cat_icon'] = array(1=>'&#xe615;', 2=>'&#xe617;', 8=>'&#xe616;', 16=>'&#xe619;');
        echo $this->load->view('scenic/checkout/ticketPop', $data, true);
        exit;
    }
    
    /**
     * 计算总金额
     */
    public function orderTotal()
    {
        $ticketId = $this->input->post('ticketId');//页面首次加载
        $buyticket = $this->input->post('buyticket');
        $buyBouns = $this->input->post('order_bouns', true);
        if (!empty($buyticket)) {
            $goodsIds = array_keys($buyticket);
        } else {
            $goodsIds = array($ticketId);
        }
        $result = $this->goods_base->orderTotal(array('goods_ids'=>$goodsIds));
        if ($result->num_rows() <= 0) {
            echo json_encode(array(
                'status' => false,
                'messages' => $this->config->wap_base_url.'scenic/home/index.html'
            ));exit;
        }
        
        $orderTotal = 0;
        $orderBouns = 0;
        $ticketTotal = array();
        foreach ($result->result() as $item) {
            $byNum = isset($buyticket[$item->goods_id]['buy_num']) ? $buyticket[$item->goods_id]['buy_num'] : 1;
            $ticketTotal[$item->goods_id] = bcmul($item->shop_price, $byNum, 2);
            $orderTotal = bcadd($orderTotal, $ticketTotal[$item->goods_id], 2);
            $orderBouns = bcadd($orderBouns, bcmul($item->off_bonus, $byNum, 2), 0);
        }
        
        $result1 = $this->user_account->findByUserAccount($this->uid);
        if ($result1->num_rows() <= 0) {
            echo json_encode(array(
                'status' => false,
                'messages' => $this->config->wap_base_url.'scenic/home/index.html'
            ));exit;
        }
        $userAccount = $result1->row(0);
        
        if ($userAccount->amount_bonus < 0 || $userAccount->amount_bonus < $orderBouns) {
            $orderBouns = 0;
        } else {
            if ($buyBouns) {
                $orderTotal = ($orderTotal-$orderBouns >= 0) ? bcsub($orderTotal, $orderBouns, 2) : $orderTotal;
            }
        }
        
        echo json_encode(array(
            'status'      => true,
            'ticketTotal' => $ticketTotal,
            'orderTotal'  => $orderTotal,
            'orderBouns'  => $orderBouns
        ));exit;
    }
    
    /**
     * 获取门票日期和价格
     * 两个月内的价格
     */
    public function getTicketDate()
    {
        $ticketId = $this->input->post('goods_id', TRUE);
        $result = $this->goods_base->findByGoodsId($ticketId);
        $ticket = $result->row(0);
        
        $sellStartTime = $ticket->sell_start_time;
        $sellEndTime = $ticket->sell_end_time;
        
        $startTime = $this->ticketStartTime($ticket);
        $startDate = strtotime(date('Y-n-j 00:00:00', $startTime));
        if ($startDate <= $ticket->sell_start_time) {
            $startDate = $ticket->sell_start_time;
        }
        
        $endDate = strtotime(date('Y-m-01') . ' +2 month -1 day');
        $days = round(($endDate-$startDate)/86400)+1;
        $dateList = array();
        for ($i=0; $i<$days; $i++) {
            $dateList[$i]['id']    = $ticket->goods_id;
            $dateList[$i]['date']  = date('Y-n-j', strtotime('+'.$i.' day', $startDate));
            $dateList[$i]['price'] = $ticket->shop_price;
        }
        echo json_encode($dateList);
        exit;
    }
    
    /**
     * 获取门票描述信息
     */
    public function ticketDescript()
    {
        $ticketId = $this->input->post('goods_id', TRUE);
        $result = $this->goods_base->findByGoodsId($ticketId);
        $data['ticket'] = $result->row(0);
        echo $this->load->view('scenic/checkout/ticketDescript', $data, true);
        exit;
    }
    
    /**
     * 获取常用联系人
     */
    public function oftenVisitor()
    {
        $data['oftenVisitor'] = $this->visitor->findByUid($this->uid);
        echo $this->load->view('scenic/checkout/oftenVisitor', $data, true);
        exit;
    }
    
    /**
     * 添加或编辑常用联系人
     */
    public function oftenVisitorModify()
    {
        $visitorId = $this->input->post('visitor_id', TRUE);
        $visitorName = $this->input->post('visitor_name', TRUE);
        if (empty($visitorName)) {
            $this->jsonMessage('姓名不能为空');
        }
        $sex = $this->input->post('sex', TRUE);  //性别 1：男
        $type = $this->input->post('type', TRUE);; //证件类型 1：身份证
        $mobilePhone = $this->input->post('mobile_phone');
        if (!validateMobilePhone($mobilePhone)) {
            $this->jsonMessage('手机号码有误');
        }
        $visitorSfz  = $this->input->post('visitor_sfz');
        if (!validateSfz($visitorSfz)) {
            $this->jsonMessage('身份证号有误');
        }
        if (!empty($visitorId) && is_numeric($visitorId)) {
            $isUpdate = $this->visitor->visitorUpdate(array('visitor_id'=>$visitorId, 'visitor_name'=>$visitorName, 'sex'=>$sex, 'mobile_phone'=>$mobilePhone, 'type'=>$type, 'pin'=>$visitorSfz));
            if (!$isUpdate) {
                $this->jsonMessage('更新失败，请稍候重试');
            }
        } else {
            $lastInsertId = $this->visitor->visitorInsert(array('uid'=>$this->uid, 'visitor_name'=>$visitorName, 'sex'=>$sex, 'mobile_phone'=>$mobilePhone, 'type'=>$type, 'pin'=>$visitorSfz));
            if (!$lastInsertId) {
                $this->jsonMessage('添加失败，请稍候重试');
            }
        }
        $data['oftenVisitor'] = $this->visitor->findByUid($this->uid);
        echo json_encode(array(
            'status'   => true,
            'messages' => $this->load->view('scenic/checkout/oftenVisitor', $data, true),
        ));exit;
    }
    
    /**
     * 景区
     * 提交，生成订单
     */
    public function orderSubmit()
    {
        if ($this->userType & UTID_PROVIDER) {
            $this->jsonMessage('供应商账号不可购买哦');
        }
        $scenicId = $this->input->post('scenicId');
        $buyticket = $this->input->post('buyticket');
        $buyBouns = $this->input->post('order_bouns', true);
        $goodsIds = $buyticket ? array_keys($buyticket) : array();
        if (empty($goodsIds)) {
            $this->jsonMessage('请添加该景区门票');
        }
        $visitorName = $this->input->post('visitor_name', TRUE);
        if (empty($visitorName)) {
            $this->jsonMessage('出行人不能为空');
        }
        $visitorSfz = $this->input->post('visitor_sfz') ? strtoupper($this->input->post('visitor_sfz', TRUE)) : 0;
        if ($visitorSfz && !validateSfz($visitorSfz)) {
            $this->jsonMessage('身份证格式不正确');
        }
        $visitorTel = $this->input->post('visitor_telephone', TRUE);
        if (!validateMobilePhone($visitorTel)) {
            $this->jsonMessage('手机号码格式不正确');
        }
        //$captcha = $this->input->post('captcha');
    
        //获取所有门票
        $result = $this->goods_base->findByParams(array('goods_ids'=>$goodsIds));
        if ($result->num_rows() <= 0) {
            $this->jsonMessage('门票信息有误');
        }
        $tickets = $result->result();
    
        //来源修改
        $payerNames = array();
        $result2 = $this->order_source->findByParams(array('goods_ids'=>$goodsIds));
        if ($result2->num_rows() > 0) {
            foreach ($result2->result() as $source) {
                if ($source->uid == 0) {
                    $payerNames[$source->goods_id] = $source->source;
                } else {
                    if ($this->uid == $source->uid) {
                        $payerNames[$source->uid][$source->goods_id] = $source->source;
                    }
                }
            }
        }
    
        $this->scenicstream->initialize(array(
            'goods_profit' => 'goods_map_profit',      //分润表
            'bargaining'   => 'goods_provider_seller', //议价表
            'user'         => 'user',                  //用户表
            'user_account' => 'user_account',
        ));
        $this->db->trans_begin();
    
        if (!$visitorSfz) { //如果未填写身份证，则发送验证码
            /*
            if (strtolower($captcha) != strtolower(get_cookie('captcha'))) {
                $this->jsonMessage('验证码输入有误！');
            }*/
    
            $lastCode = $this->make_code->findByLastId();
            $visitorSfz = intval($lastCode->row(0)->code)+1;
            $insertLast = $this->make_code->insertMakeCode($visitorSfz);
        }
    
        $payRecordId = $this->createPayRecode(); //生成pay_record记录
    
        $orderBase = array(); //订单表数据
        $scenicProfit = array(); //订单分润表数据
    
        //更新pay_record表的信息
        $level      = 0;
        $cat_ids    = array();
        $goods_ids  = array();
        $goods_nums = array();
        $order_ids  = array();
        $orderBouns = 0; //订单金币应该支付总数
        $orderPayTotal = 0;  //订单实际应该支付的总价
        $payRecordBody = ''; //订单门票购买信息
        foreach ($tickets as $key=>$ticket) {
            $goodsId = $ticket->goods_id;
            $buyDate = $buyticket[$ticket->goods_id]['buy_date']; //当前购买日期
            $buyNum  = $buyticket[$ticket->goods_id]['buy_num'];  //当前购买数量
    
            $error = $this->validateBuyTicket($ticket, $buyticket);
            if (!empty($error)) {
                $this->db->trans_rollback();
                $this->jsonMessage($error);
            }
    
            //预订延后起 + 提前预定天数可以使用
            $startTime = $this->ticketStartTime($ticket);

            //设置了当天的提前预定时间，并且购买的是次日票，则设置开始使用时间为次日的凌晨时间
            if ($ticket->advance_date <= 0 && $ticket->advance_time != '' && $ticket->advance_time > '00:00' && date('Y-m-d') < $buyDate) {
                $startTime = strtotime(date('Y-m-d 00:00:00', strtotime('+1 day')));
            }
            
            //使用有效期 - 多少天后失效
            $endTime = 0; //结束时间
            if (in_array($ticket->cat_id, array(8))) { //如果是年票 8:年票
                $endTime = strtotime(date('Y-12-31 23:59:59'));
            } else if ($ticket->validity_days > 0) {
                $startvalid = $startTime ? $startTime : time();
                $endTime = $startvalid+$ticket->validity_days*24*60*60;
            }
            if (strlen($endTime) > 11) {
                $this->db->trans_rollback();
                $this->jsonMessage('有效期结束时间有误');
            }
    
            //分润 ---- start
            $parameter = array(
                'sellerUid'   => $this->uid,
                'bitTrade'    => $this->userType,
                'parent_id'   => $this->userParentId,
                'cat_id'      => $ticket->cat_id,
                'goodsId'     => $ticket->goods_id,
                'bitWan'      => 1, //在线支付
                'number'      => $buyNum,
            );
            $profit = $this->scenicstream->scenic($parameter);
            $error = $this->scenicstream->getError();
            if (!empty($error)) {
                $this->db->trans_rollback();
                $this->jsonMessage($error);
            }
    
            $shop_price = $ticket->shop_price; //着想销售价
            $provide_price = $ticket->provide_price; //着想供应价
            $ticketPayTotal = $this->scenicstream->orderPayTotal; //当前门票需支付总价
    
            $calculate_method = $this->scenicstream->calculate_method; //1:分润 2:议价
            if ($calculate_method == 2) {
                $shop_price = $this->scenicstream->shop_price;
                $provide_price = $this->scenicstream->supply_price;
            }
    
            $orderBase['cat_id'] = $ticket->cat_id;
            $orderBase['goods_id'] = $goodsId;
            $orderBase['goods_num'] = $buyNum;
            $orderBase['payer_uid'] = $this->uid;
            $orderBase['payer_name'] = (isset($payerNames[$this->uid][$goodsId]) ? $payerNames[$this->uid][$goodsId] : (isset($payerNames[$goodsId]) ? $payerNames[$goodsId] : ($this->aliasName ? $this->aliasName : $this->userName)));
            $orderBase['bit_use'] = 0;
            $orderBase['bit_pay'] = 0; //$trade_way=4是它网过来的订单，默认是0，以支付值是65536
            //$orderBase['bit_ref'] = 0; 暂不清楚
            $orderBase['bit_opt'] = $ticket->bit_opt;
            //1官网交易 -4它网支付交易 -8景区到付 -16在线支付 -64着想或别网门票 -128议价自主结算 -258议价系统结算 -512总代结（用于统计）-2048淘宝交易 -4096去哪儿 -8192百度直达号 -16384美团交易
            $orderBase['bit_wan'] = 1|16|64;
            $orderBase['goods_name'] = $ticket->goods_name;
            $orderBase['provider_name'] = $ticket->provider_name;
            $orderBase['add_rank'] = $ticket->add_rank*$buyNum;
            $orderBase['play_name'] = $visitorName;
            $orderBase['sfz'] = $visitorSfz;
            $orderBase['phone'] = $visitorTel;
    
            $orderBase['price'] = $shop_price;
            $orderBase['number'] = $buyNum;
            $orderBase['amount_total'] = bcmul($shop_price, $buyNum, 2);
            $orderBase['amount_bouns'] = bcmul($ticket->off_bonus, $buyNum, 2);
            $orderBase['amount_fee'] = $ticketPayTotal;
            $orderBase['amount_provide'] = $provide_price; //bcmul($provide_price, $buyNum, 2);
            $orderBase['amount_second_provide'] = 0;
    
            $orderBase['pay_method'] = 0; //支付方式
            $orderBase['ordertime'] = time();
            $orderBase['paytime'] = 0;
            $orderBase['plantime'] = strtotime($buyDate);
            $orderBase['usetime'] = 0;
            $orderBase['start_time'] = $startTime;
            $orderBase['end_time'] = $endTime;
            $orderBase['mac_ids'] = $ticket->mac_ids;
            $orderBase['other_id'] = 0; //它网对接着想
            $orderBase['out_other_id'] = 0; //着想对接它网
            //$orderBase['out_other_id_is_new'] = 0; //他网单号是否是新接口对接的-着想对接他网 0-不是 1-是
            //$orderBase['api_is_new_or_old'] = 'odd'; //他网对接着想的接口是新接口还是老接口
            $orderBase['sid'] = $ticket->sid;
            //$orderBase['parent_other_id'] = 0; //合作网站父订单号--现用于百度直达号
            //$orderBase['parent_order_id'] = 0; //着想网站父订单号--现用于百度直达号
            //$orderBase['audit_id'] = 0; //合作网站退票审核id,或串码,或银行交易流水号-现用于百度直达号,银科环企网站串码,美团接口银行交易流水号,红海滩接口验证码
            //$orderBase['is_delete'] = 1;
            $orderBase['pay_id'] = $payRecordId;
            $orderBase['api_id'] = $ticket->o_api_id;
            $orderBase['is_edit'] = $ticket->is_edit;
            $orderBase['is_refund'] = $ticket->is_refund;
            $orderBase['is_partial_refund'] = $ticket->is_partial_refund;
            $orderBase['refund_day'] = $ticket->refund_day;
            $orderBase['refund_time'] = $ticket->refund_time;
            $orderBase['calculate_method'] = $calculate_method; //1:分润；2:议价
            $orderBase['order_source'] = 2; //1:PC端；2:手机端
    
            $orderId = $this->order_base->insertOrderBase($orderBase);
            //$update = $this->goods_base->setTicketStock(array('goods_id'=>$goodsId, 'limit_number'=>-$buyNum)); //下单时减去库存
    
            //景区订单分润表
            $scenicProfit[$orderId] = $profit;
    
            $level = $level|$ticket->cat_id;
            $cat_ids[] = $ticket->cat_id;
            $goods_ids[] = $ticket->goods_id;
            $goods_nums[] = $buyNum;
            $order_ids[] = $orderId;
            $orderBouns += bcmul($ticket->off_bonus, $buyNum, 2);
            $orderPayTotal += $ticketPayTotal; //订单实际应该支付的总价
            $payRecordBody .= $ticket->goods_name.'['.$buyNum.'张]';
        }
        $profitBatch = $this->order_profit->insertBatch($scenicProfit);
        
        /*-------订单修改--------*/
        if ($buyBouns && $buyBouns<=$orderBouns) { //是否选择使用金币
            $orderBouns = $buyBouns;
        }
        $payRecord['pay_id']     = $payRecordId;
        $payRecord['uid']        = $this->uid;
        $payRecord['level']      = $level;
        $payRecord['cat_ids']    = serialize($cat_ids);
        $payRecord['goods_ids']  = serialize($goods_ids);
        $payRecord['goods_nums'] = serialize($goods_nums);
        $payRecord['order_ids']  = serialize($order_ids);
        $payRecord['order_bouns']= $orderBouns;
        $payRecord['amount']     = $orderPayTotal;
        $payRecord['body']       = $payRecordBody;
        $updatePay = $this->pay_record->updatePayRecord($payRecord);
    
        if ($this->db->trans_status() === FALSE && !$payRecordId && $profitBatch && $updatePay) {
            $this->db->trans_rollback();
            $this->jsonMessage('订单生成失败');
        }
        $this->db->trans_commit();
    
        $this->jsonMessage('', site_url('scenic/payment/payOrderScenic/'.$payRecordId));
    }
    
    /**
     * 验证购买门票的信息
     * @param unknown $ticket
     * @param unknown $buyticket
     */
    public function validateBuyTicket($ticket, $buyticket)
    {
        $goodsId = $ticket->goods_id;
        $buyDate = $buyticket[$ticket->goods_id]['buy_date']; //当前购买日期
        $buyNum  = $buyticket[$ticket->goods_id]['buy_num'];  //当前购买数量
        
        //销售时间
        if ($ticket->sell_start_time != 0 && ($buyDate < date('Y-m-d', $ticket->sell_start_time) || time() < $ticket->sell_start_time)) {
            return $ticket->goods_name.'不在销售时间内或者购买日期未到有效期';
        }
        if ($ticket->sell_end_time != 0 && (strtotime($buyDate) > $ticket->sell_end_time || time() > $ticket->sell_end_time)) {
            return $ticket->goods_name.'超出可售时间或者购买日期已超出有效期';
        }
        
        //验证库存
        if ($buyNum > $ticket->limit_number) {
            return $ticket->goods_name.'当前购买张数大于实际库存'.$ticket->limit_number.'张';
        }
    
        //验证限制用户购买数量
        if ($buyNum < $ticket->min_number) {
            return $ticket->goods_name.'购买张数必须要大于等于最小购买张数（'.$ticket->min_number.'）张';
        }
    
        //验证提前预订天数
        if ($ticket->advance_date > 0 && (strtotime($buyDate.' 23:59:59') - $ticket->advance_date*24*60*60) < time()) {
            return $ticket->goods_name.'需提前'.$ticket->advance_date.'天预订';
        }
    
        //验证提前预订时间 -- //当计算出来的日期时间小于(当前时间+提前预订天数)
        if (!empty($ticket->advance_time) && strtotime($buyDate.' '.$ticket->advance_time) < (time() + $ticket->advance_date*24*60*60)) {
            if ($ticket->advance_date > 0) {
                return $ticket->goods_name.'需提前'.$ticket->advance_date.'天，并且需在'.$ticket->advance_time.'之前预订';
            } else {
                return $ticket->goods_name.'需在'.$ticket->advance_time.'之前预订';
            }
        }
    
        //指定购买者
        if (!empty($ticket->buyers) && !in_array($this->uid, explode('|', $ticket->buyers))) {
            return $ticket->goods_name.'只有指定的用户才可以购买';
        }
    
        //指定不可购买者
        if (!empty($ticket->unbuyers) && in_array($this->uid, explode('|', $ticket->unbuyers))) {
            return '抱歉，您不能购买'.$ticket->goods_name.'门票';
        }
    
        //验证身份证的有效性
        $visitorSfz = $this->input->post('visitor_sfz');
        if (!empty($visitorSfz)) {
            validateSfz($visitorSfz);
        }
    
        //除了周末时间，均可购买
        if ($ticket->bit_opt&4096) {
            $weekDay = date('w', strtotime($buyDate));
            if (!in_array($weekDay, array(1,2,3,4,5))) {
                return '抱歉，'.$ticket->goods_name.'属于日常票，除了周末时间均可购买';
            }
        }
    
        //只能周末时间购买
        if ($ticket->bit_opt&8192) {
            $weekDay = date('w', strtotime($buyDate));
            if (in_array($weekDay, array(1,2,3,4,5))) {
                return '抱歉，'.$ticket->goods_name.'属于周末票，请选择周末时间购买';
            }
        }
    
        //限止一个身份证能购买一种类型门票的最大张数,以预订频次限制为标准
        if ($ticket->limit_sfz_number > 0) {
            $buy_number = 0; //已购买数量
            $result = $this->order_base->findByParams(array('select'=>'number,ordertime', 'sfz'=>$visitorSfz, 'goods_id'=>$goodsId, 'bit_pay'=>0, 'goods_num'=>0));
            if ($result->num_rows() > 0) {
                $order_result = $result->result();//获得多条记录
                switch ($ticket->sfz_booking_limit) {
                    case 1: //1天:可以多次购买,但1天之内只能购买不大于最大数的门票数
                        foreach ($order_result as $value) {
                            $order_time_date = date('Y-m-d', $value->ordertime);//之前下单日期
                            $current_order_date = date('Y-m-d');//当前下单日期
                            //如果之前下单日期等于当前下单日期,已购买订单数量就等于之前下单数量的总和
                            if ($order_time_date == $current_order_date) {
                                $buy_number += $value->number;
                            }
                        }
                        break;
                    case 2: //1周:可以多次购买,但1周之内只能购买不大于最大数的门票数
                        foreach ($order_result as $value) {
                            $order_time_week = date('W', $value->ordertime);//根据之前下单时间戳计算是一年中的第几周
                            $current_order_week = date('W', time());//根据当前下单时间戳计算是一年中的第几周
                            //如果之前下单周数等于当前下单周数,已购买订单数量就等于之前下单数量的总和
                            if ($order_time_week == $current_order_week) {
                                $buy_number += $value->number;
                            }
                        }
                        break;
                    case 3: //1月:可以多次购买,但1月之内只能购买不大于最大数的门票数
                        foreach ($order_result as $value) {
                            $order_time_month = date('Y-m', $value->ordertime);//根据之前下单月份
                            $current_order_month = date('Y-m');//根据当前下单月份
                            //如果之前下单月份等于当前下单月份,已购买订单数量就等于之前下单数量的总和
                            if ($order_time_month == $current_order_month) {
                                $buy_number += $value->number;
                            }
                        }
                        break;
                    case 4: //1年:可以多次购买,但1年之内只能购买不大于最大数的门票数
                        foreach ($order_result as $value) {
                            $order_time_year = date('Y', $value->ordertime);//根据之前下单年份
                            $current_order_year = date('Y');//根据当前下单年份
                            //如果之前下单年份等于当前下单年份,已购买订单数量就等于之前下单数量的总和
                            if ($order_time_year == $current_order_year) {
                                $buy_number += $value->number;
                            }
                        }
                        break;
                    case 0: //无限制:可以多次购买,但一次购买的数量不能超过最大数
                    default:
                        break;
                }
            }
            //已购买的票数+当前购买票数大于限制购买的最大票数
            if (($buy_number+$buyNum) > $ticket->limit_sfz_number) {
                return $ticket->goods_name.'当前身份证超出限制购买张数（'.($buy_number+$buyNum-$ticket->limit_sfz_number).'）张';
            }
        }
    
        //限止指定地区不能购买
        if (!empty($ticket->limit_area)) {
            $limitArea = explode('|', $ticket->limit_area);
            $flag = false;
            foreach($limitArea as $shortArea) {
                if (!empty($shortArea)) {
                    $shortSfz = mb_substr($visitorSfz, 0, strlen($shortArea));
                    if ($shortSfz == $shortArea) {
                        $flag = true;
                    }
                }
            }
            if ($flag) {
                return '抱歉，由于区域限制，您的身份证不能购买'.$ticket->goods_name.'门票';
            }
        }
    
        //限止指定地区可以购买
        if (!empty($ticket->access_area)) {
            $accessArea = explode('|', $ticket->access_area);
            $flag = true;
            foreach ($accessArea as $shortAccess) {
                if (!empty($shortAccess)) {
                    $short_sfz = mb_substr($visitorSfz, 0, strlen($shortAccess));
                    if ($short_sfz == $shortAccess) {
                        $flag = false;
                    }
                }
            }
    
            if ($flag) {
                return '抱歉，由于区域限制，您的身份证不能购买'.$ticket->goods_name.'门票';
            }
        }
    }
    
    /**
     * 获取下单开始生效时间
     * @param unknown $ticket
     * @return number
     */
    public function ticketStartTime($ticket)
    {
        $startTime = 0; //开始时间 = 当前下单时间
        $today = strtotime(date('Y-m-d 00:00:00'));
        if ($ticket->use_start_day > 0) {
            $startTime = time();
            if ((date('H') - 21) >= 0) {
                if ((int)$ticket->use_start_day < 24) {
                    $startTime = $startTime+$ticket->use_start_day*60*60;
                } else {
                    $startTime = $today+($ticket->use_start_day + 24 - date('H'))*60*60;
                }
            } else {
                if ((int)$ticket->use_start_day < 24) {
                    $startTime = $startTime+$ticket->use_start_day*60*60;
                } else {
                    $startTime = $today +($ticket->use_start_day)*60*60;
                }
            }
        }
    
        //如果设置提前预定天数
        if ($ticket->advance_date > 0) {
            if ($startTime) {
                $startTime = $startTime + $ticket->advance_date*24*60*60;
            } else {
                $startTime = $today + $ticket->advance_date*24*60*60;
            }
        }
        if (empty($startTime)) { //如果开始时间为零，则默认当前时间
            $startTime = time();
        }
        return $startTime;
    }
    
    /**
     * 生成订单pay_record表数据
     */
    public function createPayRecode()
    {
        $payRecord = array(); //订单支付
        $payRecord['level'] = 0;
        $payRecord['cat_ids'] = 0;
        $payRecord['goods_ids'] = 0;
        $payRecord['goods_nums'] = 0;
        $payRecord['order_ids'] = 0;
        $payRecord['uid'] = $this->uid;
        $payRecord['phone'] = $this->input->post('visitor_telephone');
        $payRecord['pay_method'] = 0;
        $payRecord['amount'] = 0; //需支付总金额
        $payRecord['subject'] = '交易款';
        $payRecord['body'] = '';
        $payRecord['info'] = '0';
        $payRecord['bit_state'] = 0;
        $payRecord['pay_time'] = 0;
    
        return $this->pay_record->insertPayRecord($payRecord);
    }
}
